package com.googlecode.olabs.common.client.contact.formats.json;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.googlecode.olabs.common.client.contact.Contact;
import com.googlecode.olabs.common.client.contact.ContactException;
import com.googlecode.olabs.common.client.contact.field.Field;
import com.googlecode.olabs.common.client.contact.formats.Renderer;

public class JsonRenderer implements Renderer {

	public List<String> render(Contact contact) throws ContactException {
		StringBuilder result = new StringBuilder();

		result.append("{\"");
		result.append(JsonFormat.KEY_FORMAT);
		result.append("\":\"");
		result.append(JsonFormat.VALUE_FORMAT);
		result.append("\",\"");
		result.append(JsonFormat.KEY_VERSION);
		result.append("\":\"");
		result.append(JsonFormat.VALUE_VERSION);
		result.append("\",\"");
		result.append(JsonFormat.KEY_FIELDS);
		result.append("\":");

		Collection<Field> fields = contact.getFields();
		if (fields.size() == 0) {
			result.append("null");
		} else {
			result.append(renderFields(fields));
		}

		result.append("}");

		List<String> list = new ArrayList<String>(1);
		list.add(result.toString());
		return list;
	}

	private String renderFields(Collection<Field> fields) {
		StringBuilder result = new StringBuilder();
		result.append("[");

		boolean firstField = true;
		for (Field field : fields) {
			if (firstField) {
				firstField = false;
			} else {
				result.append(",");
			}
			result.append("{\"");
			result.append(JsonFormat.KEY_FIELD_TYPE);
			result.append("\":\"");
			result.append(field.getType());
			result.append("\",\"");
			result.append(JsonFormat.KEY_FIELD_SUBTYPE);
			result.append("\":");
			if (field.getSubTypes().size() == 0) {
				result.append("null,");
			} else {
				result.append("[");
				boolean firstSubType = true;
				for (String subType : field.getSubTypes()) {
					if (firstSubType) {
						firstSubType = false;
					} else {
						result.append(",");
					}
					result.append("\"");
					result.append(subType);
					result.append("\"");
				}
				result.append("],");
			}
			result.append(JsonFormat.KEY_FIELD_VALUE);
			result.append("\":[");
			boolean firstValue = true;
			for (String value : field.getValue()) {
				if (firstValue) {
					firstValue = false;
				} else {
					result.append(",");
				}
				result.append("\"");
				result.append(value);
				result.append("\"");
			}
			result.append("]}");
		}

		result.append("]");
		return result.toString();
	}
}
